package com.nofeng.wx.utils;

import com.google.common.collect.Lists;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Base64;

/**
 * AES加解密工具类
 */
public class AesUtils {

    public static void main(String[] args) {
        try {
            //私钥
            String secretKey = "46cc793c53dc451b";

            //手机号用例
            String plaintext = "11111112222";
            String plaintext2 = "123456745910";
            ArrayList<String> plainList = Lists.newArrayList(plaintext, plaintext2);
            System.out.println("私钥:"+secretKey);
            for (String mobile : plainList) {
                System.out.println("\n" + mobile);
                // 加密
                String encryptedText = encrypt(mobile, secretKey);
                System.out.println("Encrypted: " + encryptedText);
                // 解密
                String decryptedText = decrypt(encryptedText, secretKey);
                System.out.println("Decrypted: " + decryptedText);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String encrypt(String plaintext, String secretKey) throws Exception {
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        byte[] secretKeyBytes = secretKey.getBytes(StandardCharsets.UTF_8);
        SecretKeySpec secretKeySpec = new SecretKeySpec(secretKeyBytes, "AES");
        IvParameterSpec ivSpec = new IvParameterSpec(secretKeyBytes);
        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivSpec);
        byte[] encryptedBytes = cipher.doFinal(plaintext.getBytes(StandardCharsets.UTF_8));
        return Base64.getEncoder().encodeToString(encryptedBytes);
    }

	public static String decrypt(String encryptedText, String secretKey) throws Exception {
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        byte[] secretKeyBytes = secretKey.getBytes(StandardCharsets.UTF_8);
        SecretKeySpec secretKeySpec = new SecretKeySpec(secretKeyBytes, "AES");
        IvParameterSpec ivSpec = new IvParameterSpec(secretKeyBytes);
        cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivSpec);
        byte[] encryptedBytes = Base64.getDecoder().decode(encryptedText);
        byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
        return new String(decryptedBytes, StandardCharsets.UTF_8);
    }


}
